package com.control;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.QueryStringDecoder;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.io.UnsupportedEncodingException;

import com.server.Util;

import io.netty.buffer.Unpooled;

public class HttpServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof HttpRequest) {
			// 请求，解码器将请求转换成HttpRequest对象
			HttpRequest request = (HttpRequest) msg;
			if (!request.decoderResult().isSuccess()) {
				Util.sendError(ctx, HttpResponseStatus.BAD_REQUEST);
				return;
			}
			//			if (request.method() != HttpMethod.GET) {
			//				Util.sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
			//				return;
			//			}

			// 获取queryString请求参数
			QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
			//	            String name = "netty";
			//	            if(queryStringDecoder.parameters().get("name") != null) {
			//	                    name = queryStringDecoder.parameters().get("name").get(0);
			//	            }

			// 响应HTML
			String responseHtml = "Hello";
			FullHttpResponse response = setResponseHeaders(request, responseHtml);
			ctx.writeAndFlush(response);
		}
	}

	//请求完成
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	//请求异常处理
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}

	private FullHttpResponse setResponseHeaders(HttpRequest request, String responsebody)
			throws UnsupportedEncodingException {
		byte[] responseBytes = responsebody.getBytes("UTF-8");
		return setResponseHeaders(request, responseBytes);
	}

	/**
	* 设置HTTP返回头信息
	*/
	private FullHttpResponse setResponseHeaders(HttpRequest request, byte[] responseBytes) {
		// byte[] responseBytes = responsebody.getBytes("UTF-8");
		// 构造FullHttpResponse对象，FullHttpResponse包含message body
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(responseBytes));
		response.headers().set("Content-Type", "text/html; charset=utf-8");
	//	response.headers().set("Content-Type", "application/json; charset=utf-8");
		//response.headers().set("Content-Type", "text/javascript;charset=UTF-8");
		int contentLength = responseBytes.length;
		response.headers().set("Content-Length", Integer.toString(contentLength));
		if (HttpUtil.isKeepAlive(request)) {
			response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
		}
		return response;
	}

	/**
	 * 设置JSESSIONID
	 */
	private void setJsessionId(boolean isHasJsessionId) {
		if (!isHasJsessionId) {
			//            CookieEncoder encoder = new CookieEncoder(true);
			//            encoder.addCookie(HttpSession.SESSIONID, HttpSessionManager.getSessionId());
			//            String encodedCookie = encoder.encode(); 
			//            response.headers().set(HttpHeaderNames.SET_COOKIE, encodedCookie); 
		}
	}

	/**
	 * 从cookie中获取JSESSIONID信息
	 * 判断服务器是否有客户端的JSESSIONID
	 * @author yangsong
	 * @date 2015年3月26日 下午2:08:07
	 */
	private boolean isHasJsessionId(HttpRequest request) {
		try {
			//            String cookieStr = request.headers().get("Cookie");
			//            Set<Cookie> cookies = ServerCookieDecoder.decode(cookieStr);
			//            Iterator<Cookie> it = cookies.iterator();
			//            
			//            while(it.hasNext()){
			//                Cookie cookie = it.next();
			//                if(cookie.getName().equals(HttpSession.SESSIONID)){
			//                    if(HttpSessionManager.isHasJsessionId(cookie.getValue())){
			//                        return true;
			//                    }
			//                    System.out.println("JSESSIONID:"+cookie.getValue());
			//                        
			//                }
			//            }
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return false;
	}
}
